package com.songcha.module_login.ui.activity.login

import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.songcha.library_base.mvvm.base.BaseMvvmActivity
import com.songcha.library_business.LibraryBusinessApplication
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.event.wx.WXLoginRespEvent
import com.songcha.library_business.helper.UMengHelper
import com.songcha.library_business.helper.WxHelper
import com.songcha.library_business.util.BusinessJumpUtil
import com.songcha.library_business.util.MajiaBaoUtil
import com.songcha.library_common.LibraryCommon
import com.songcha.library_common.ui.dialog.LoadingDialog
import com.songcha.library_common.util.ColorUtil
import com.songcha.library_common.util.PackageUtil
import com.songcha.library_common.util.RegexUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.module_login.R
import com.songcha.module_login.databinding.LoginActivityLoginBinding
import com.songcha.module_login.ui.activity.user_privacy.UserPrivacyActivity
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.util.concurrent.TimeUnit


@Route(path="/login/LoginActivity")
class LoginActivity :BaseMvvmActivity<LoginViewModel,LoginActivityLoginBinding>() {
    private var mSendVerifyDispose:Disposable?=null
    private var mLoadingDialog:Dialog?=null

    override fun getLayoutId(): Int {
        return R.layout.login_activity_login
    }

    override fun isImmerseStatusBar(): Boolean {
        return true
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        if(FunctionConfig.IS_WX_LOGIN_ENABLED){
            databinding.loginIvWxlogin.visibility=View.VISIBLE
        }else{
            databinding.loginIvWxlogin.visibility=View.GONE
        }

        databinding.loginTvTip.apply {
           text = text.toString().replace("\${app_name}",PackageUtil.getAppName(this@LoginActivity))
        }

        viewModel.verifyCountDown.observe(this){
            updateTvSendVerify(it)
        }

        viewModel.sendVerifySuccess.observe(this){
            handleSendVerifyResult(it)
        }

        viewModel.loginState.observe(this){data->
            handleLoginState(data)
            if(data==LoginViewModel.LoginState.SUCCESS){
                UMengHelper.onUMEvent(this,"phone_login_success")
            }else{

            }
        }

        viewModel.wxLoginState.observe(this){data->
            handleLoginState(data)
            if(data==LoginViewModel.LoginState.SUCCESS){
                UMengHelper.onUMEvent(this,"wx_login_success")
            }else{
                UMengHelper.onUMEvent(this,"wx_login_error")
            }
        }


        databinding.loginIvBack.setOnClickListener {
            finish()
        }

        databinding.loginTvSendVerify.setOnClickListener {
            sendVerify()
        }

        databinding.loginBtnLogin.setOnClickListener{
           login()
        }

        databinding.loginIvWxlogin.setOnClickListener{
            wxlogin()
        }

        databinding.loginCcb.setIsCheck(viewModel.isCheckPrivacyPolicy)
        databinding.loginCcb.setOnCheckListener{isCheck->
            viewModel.isCheckPrivacyPolicy=isCheck
            viewModel.setCheckPrivacyPolicy(isCheck)
        }


       /* databinding.loginTvUserProtocol.setOnClickListener{
            val intent=Intent(it.context,UserPrivacyActivity::class.java)
            intent.putExtra("is_privacy",false)
            startActivity(intent)
        }

        databinding.loginTvPrivacyPolicy.setOnClickListener{
            val intent=Intent(it.context,UserPrivacyActivity::class.java)
            intent.putExtra("is_privacy",true)
            startActivity(intent)
        }*/



        val ssb = SpannableString("已阅读并同意《用户协议》与《隐私政策》")
        val userProtocolClickSpan=object : ClickableSpan(){
            override fun onClick(widget: View) {
                BusinessJumpUtil.toUserPrivacyActivity(widget.context,1)
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color=ColorUtil.getResourceColor(this@LoginActivity,com.songcha.library_common.R.color.primary)
                ds.isUnderlineText=false
            }

        }
        val privacyPolicyClickSpan=object : ClickableSpan(){
            override fun onClick(widget: View) {
                BusinessJumpUtil.toUserPrivacyActivity(widget.context,2)
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color=ColorUtil.getResourceColor(this@LoginActivity,com.songcha.library_common.R.color.primary)
                ds.isUnderlineText=false
            }
        }

        ssb.setSpan(userProtocolClickSpan, 6, 12, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
        ssb.setSpan(privacyPolicyClickSpan, 13, 19, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
        databinding.loginTvUserPrivacy.movementMethod=(LinkMovementMethod())
        databinding.loginTvUserPrivacy.text = ssb

        EventBus.getDefault().register(this)

    }


    private fun handleLoginState(state:LoginViewModel.LoginState){
        mLoadingDialog?.dismiss()
        if(state==LoginViewModel.LoginState.SUCCESS){
            ToastUtil.show("登录成功")
            finish()
        }else{

        }
    }

    private fun handleSendVerifyResult(isSuccess: Boolean){
        if(isSuccess){
            ToastUtil.show("验证码发送成功")
        }else{
            mSendVerifyDispose?.dispose()
            UMengHelper.onUMEvent(this,"phone_login_sendverify_error")
        }
    }

    private fun updateTvSendVerify(countDown:Int){
        if(countDown==0){
            databinding.loginTvSendVerify.text="发送验证码"
            //databinding.loginTvSendVerify.setTextColor(Color.parseColor("#635F5F"))
        }else{
            databinding.loginTvSendVerify.text="重新获取（${countDown}s）"
            //databinding.loginTvSendVerify.setTextColor(Color.parseColor("#6D90E0"))
        }
    }

    private fun wxlogin() {
        if (!databinding.loginCcb.isCheck()) {
            ToastUtil.show(resources.getString(R.string.login_please_agreen_protocol))
            return
        }

        if (!WxHelper.wxlogin()) {
            UMengHelper.onUMEvent(this, "wx_login_not_install_wx")
        }
    }

    private fun login(){
        if(!databinding.loginCcb.isCheck()) {
            ToastUtil.show(resources.getString(R.string.login_please_agreen_protocol))
            return
        }
        val phone=databinding.loginEdtPhone.text.toString().trim()
        if(!checkPhone(phone)) return
        val verifyCode=databinding.loginEdtVerify.text.toString().trim()
        if(verifyCode.isEmpty()){
            ToastUtil.show(resources.getString(R.string.login_please_input_verify))
            return
        }

        UMengHelper.onUMEvent(this,"phone_click_login")

        mLoadingDialog=LoadingDialog(this)
        mLoadingDialog!!.show()

        viewModel.login(phone,verifyCode)
    }


    private fun sendVerify(){
        if(viewModel.verifyCountDown.value!!>0){
            return
        }
        val phone=databinding.loginEdtPhone.text.toString().trim()
        if(!checkPhone(phone)) return

        mSendVerifyDispose?.dispose()
        mSendVerifyDispose = Observable.intervalRange(0,60,0,1,TimeUnit.SECONDS)
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe{
                viewModel.setCountDown(59-it.toInt())
            }

        viewModel.sendVerify(phone)
    }

    private fun checkPhone(phone:String):Boolean{
        if(phone.isEmpty()){
            ToastUtil.show(resources.getString(R.string.login_please_input_phone))
            return false
        }
        if(!RegexUtil.isPhone(phone)){
            ToastUtil.show(resources.getString(R.string.login_invalid_phone))
            return false
        }
        return true
    }

    @Subscribe
    fun onWXLoginResp(event:WXLoginRespEvent){
        if(event.errCode==0){
            viewModel.wxlogin(event.code)
        }else if(event.errCode==-2){
            ToastUtil.show("用户取消微信登录")
            UMengHelper.onUMEvent(this,"wx_login_cancel")
        }else{
            ToastUtil.show("微信登录异常")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

}